package com.ruoyi.web.controller.system;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.ruoyi.common.config.AliConfig;
import com.ruoyi.common.config.AlipayToken;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ErrorResponse;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;


    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @PostMapping("/getAlipayToken")
    public AjaxResult getToken(@RequestBody String authCode){
        System.out.println("suthCode="+authCode);
        AjaxResult ajaxResult = AjaxResult.success();

        AliConfig.alipayClient = new DefaultAlipayClient(AliConfig.aliPayURL, AliConfig.appId,
                AliConfig.privateKey, "json", "utf-8", AliConfig.publicKey, "RSA2");

        //向支付宝api获取token
        AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest();
        //设置请求类型和从前端得到的authCode
        oauthTokenRequest.setGrantType(AliConfig.grantType);
        oauthTokenRequest.setCode(authCode);
        //向支付宝api获取用户登录信息请求
        AlipayUserInfoShareRequest userInfoShareRequest = new AlipayUserInfoShareRequest();
        try {
            AlipaySystemOauthTokenResponse tokenResponse = AliConfig.alipayClient.execute(oauthTokenRequest);
            if (tokenResponse.isSuccess()){
                AlipayToken.refreshToken= tokenResponse.getRefreshToken();
                AlipayToken.authStart=  tokenResponse.getAuthStart();
                AlipayToken.userId= tokenResponse.getUserId();
                AlipayToken.access_token=tokenResponse.getAccessToken();
                AlipayToken.expiresIn=tokenResponse.getExpiresIn();
                AlipayToken.reExpiresIn= tokenResponse.getReExpiresIn();
                System.out.println("token:"+tokenResponse.getAccessToken());
                System.out.println("AlipaySystemOauthTokenResponse userId:"+tokenResponse.getUserId());
                AlipayUserInfoShareResponse userInfoShareResponse = AliConfig.alipayClient.execute(userInfoShareRequest, tokenResponse.getAccessToken());
                String token = loginService.login("admin", "admin123", "", "", AlipayToken.userId);
                ajaxResult.put(Constants.TOKEN, token);
                return ajaxResult;
//                if (userInfoShareResponse.isSuccess()){
//                    System.out.println("获取信息成功"+userInfoShareResponse.getBody());
//
//                }else {
//                    return AjaxResult.error("获取token信息失败2",userInfoShareResponse.getSubMsg());
//                }
//                return ajaxResult.put("token",tokenResponse.getAccessToken());
            }else {
                ErrorResponse errorResponse = new ErrorResponse(tokenResponse.getCode(),tokenResponse.getMsg(),tokenResponse.getSubCode(),tokenResponse.getSubMsg());
                return AjaxResult.error("获取token失败1",errorResponse);
            }

        } catch (AlipayApiException e) {
            return AjaxResult.error("获取token失败",e);
        }
    }



    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
